package edu.polsl.bio.str.manager.messaging;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageChannel;
import org.springframework.integration.jms.JmsSendingMessageHandler;
import org.springframework.jms.core.JmsTemplate;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * //todo class description
 * <p/>
 * Created on: Jun 15, 2011 4:08:51 PM <br/>
 * <a href="http://www.polsl.pl">www.polsl.pl</a>
 *
 * @author lukasz.olczak@polsl.pl
 */
public class JmsQueueLocator implements QueueLocator {
  /**
   * slf4j Logger.
   */
  private static final Logger log = LoggerFactory.getLogger(JmsQueueLocator.class.getName());

  private Map<String, MessageChannel> queueMap;

  private String jmsPort;

  private String jmsQueueName;

  public JmsQueueLocator() {
    queueMap = new ConcurrentHashMap();
  }

  private MessageChannel lookupQueue(String host, String port, String queueName) {
    log.debug("Looking up jms queue {} for {}", queueName, host);
    ActiveMQConnectionFactory jmsFactory = new ActiveMQConnectionFactory("tcp://" + host + ":" + port);
    JmsTemplate jmsTemplate = new JmsTemplate(jmsFactory);
    jmsTemplate.setDefaultDestinationName(queueName);
    jmsTemplate.afterPropertiesSet();
    JmsSendingMessageHandler msgHandler = new JmsSendingMessageHandler();
    msgHandler.setJmsTemplate(jmsTemplate);
    msgHandler.afterPropertiesSet();
    DirectChannel directChannel = new DirectChannel();
    directChannel.subscribe(msgHandler);
    return directChannel;
  }

  @Override
  public MessageChannel getNodeJobChannel(String nodeIp) {
    MessageChannel msgChannel = queueMap.get(nodeIp);
    if (msgChannel == null) {
      msgChannel = lookupQueue(nodeIp, jmsPort, jmsQueueName);
      queueMap.put(nodeIp, msgChannel);
    }

    return msgChannel;
  }

  @Override
  public void flushProxy(String nodeIp) {
    queueMap.remove(nodeIp);
  }

  public void setJmsPort(String jmsPort) {
    this.jmsPort = jmsPort;
  }

  public void setJmsQueueName(String jmsQueueName) {
    this.jmsQueueName = jmsQueueName;
  }
}
